package com.aistar.service.impl;

import com.aistar.pojo.ReviewAgree;
import com.aistar.service.RedisService;
import com.aistar.util.CreatRedisKeyUtil;
import com.aistar.util.LikedCountDTO;
import com.aistar.util.LikedStatusEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.Cursor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ScanOptions;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class RedisServiceImpl implements RedisService {

    @Autowired
    RedisTemplate redisTemplate;


    /**
     * 点赞。状态为1
     * @param likedUserId
     * @param likedPostId
     */
    @Override
    public void saveLiked2Redis(String likedUserId, String likedPostId) {
        String key = CreatRedisKeyUtil.getLikedKey(likedUserId, likedPostId);
        redisTemplate.opsForHash().put(CreatRedisKeyUtil.MAP_KEY_USER_LIKED, key, LikedStatusEnum.LIKE.getCode());
    }


    /**
     * 取消点赞。将状态改变为0
     * @param likedUserId
     * @param likedPostId
     */
    @Override
    public void unlikeFromRedis(String likedUserId, String likedPostId) {
        String key = CreatRedisKeyUtil.getLikedKey(likedUserId, likedPostId);
        redisTemplate.opsForHash().put(CreatRedisKeyUtil.MAP_KEY_USER_LIKED, key, LikedStatusEnum.UNLIKE.getCode());
    }

    /**
     * 获取Redis中存储的所有点赞数量
     * @return
     */
    @Override
    public List<LikedCountDTO> getLikedCountFromRedis() {
        Cursor<Map.Entry<Object, Object>> cursor = redisTemplate.opsForHash().scan(CreatRedisKeyUtil.MAP_KEY_USER_LIKED_COUNT, ScanOptions.NONE);
        List<LikedCountDTO> list = new ArrayList<>();
        while (cursor.hasNext()){
            Map.Entry<Object, Object> map = cursor.next();
            //将点赞数量存储在 LikedCountDT
            String key = (String)map.getKey();
            LikedCountDTO dto = new LikedCountDTO(key, (Integer) map.getValue());
            list.add(dto);
            //从Redis中删除这条记录
            redisTemplate.opsForHash().delete(CreatRedisKeyUtil.MAP_KEY_USER_LIKED_COUNT, key);
        }
        return list;
    }


    @Override
    public List<LikedCountDTO> getAndDeleteLikedCountFromRedis() {
        Cursor<Map.Entry<Object, Object>> cursor = redisTemplate.opsForHash().scan(CreatRedisKeyUtil.MAP_KEY_USER_LIKED, ScanOptions.NONE);
        List<LikedCountDTO> list = new ArrayList<>();
        while (cursor.hasNext()){
            Map.Entry<Object, Object> map = cursor.next();
            //将点赞数量存储在 LikedCountDT
            String key = (String)map.getKey();
            LikedCountDTO dto = new LikedCountDTO(key, (Integer) map.getValue());
            list.add(dto);
            //从Redis中删除这条记录
            redisTemplate.opsForHash().delete(CreatRedisKeyUtil.MAP_KEY_USER_LIKED, key);
        }
        return list;
    }
}
